package br.ucb.sigplan.action.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperPrint;
import br.ucb.sigplan.action.Action;
import br.ucb.sigplan.beans.PlanoEnsino;
import br.ucb.sigplan.beans.Turma;
import br.ucb.sigplan.crud.PlanoEnsinoCrud;
import br.ucb.sigplan.util.JasperUtil;

public class JasperPlanoEnsinoAction implements Action {

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Integer idTurma = new Integer(req.getParameter("idTurma"));
		PlanoEnsino plano = PlanoEnsinoCrud.findByTurma(new Turma(idTurma));
		if (plano == null) {
			req.setAttribute("msg", "planoNaoCadastrado");
			return "/jsp/index.jsp";
		}
		List<PlanoEnsino> planos = new ArrayList<PlanoEnsino>();
		planos.add(plano);
		try {
			JasperPrint jprint = JasperUtil.getJasperPrint(req.getSession().getServletContext().getRealPath("/Relatorio/plano.jasper"), planos,
					req.getSession().getServletContext().getRealPath("images/catolica.png"));
			

			OutputStream outStream = resp.getOutputStream();
			resp.setContentType("application/pdf");
			resp.setHeader("Content-Disposition","attachment; filename=plano_de_ensino.pdf");
			//resp.addHeader("filename", "\"plano_de_ensino.pdf\"");
			
			JasperExportManager.exportReportToPdfStream(jprint, outStream);	
		} catch (JRException e) {
			e.printStackTrace();
		}
		return null;
	}

}
